package com.wondedDream.jwt;

import com.wondedDream.jwt.annotation.JwtTokenRequired;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

@Aspect
@Component
public class JwtAspect {

    @Autowired
    private JwtUtils jwtUtils;

    @Pointcut("execution(public * *(..)) && @annotation(com.wondedDream.jwt.annotation.JwtTokenRequired)")
    public void jwtTokenRequired() {
    }


    @Before("jwtTokenRequired()")
    public void before(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        if (method.isAnnotationPresent(JwtTokenRequired.class)) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();
            String token = request.getHeader("Authorization");
            if (token == null ||!token.startsWith("Bearer ")) {
                throw new RuntimeException("Invalid Token");
            }
            token = token.substring(7);
            if (!jwtUtils.validateToken(token)) {
                throw new RuntimeException("Token is invalid or expired");
            }
        }
    }
}